﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;
using rsdeploygui.ReportService2010;

namespace rsdeploygui
{
    class DataSource
    {
        private ReportingService2010 rs;

        public DataSource (string url)
        {
            try
            {
                rs = new ReportingService2010();
                rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
                rs.Url = url;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Get the data source definition
        /// </summary>
        /// <param name="srcPath"></param>
        /// <returns></returns>
        public DataSourceDefinition getDataSourceDef(string srcPath)
        {
            DataSourceDefinition dsdef = null;

            try
            {
                Uri server = new Uri(this.rs.Url.ToString());
                //  GetDatasourceContents expects a full URL in this format
                // http://hostname/reportserver/parentpath/dsname.rsds 
                string url = "http://" + server.Host + "reportserver" + srcPath + ".rsds";
                dsdef = this.rs.GetDataSourceContents(srcPath);
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.Detail.InnerText);
            }

            return dsdef;
        }

        public Boolean createDataSource(string parentPath, string dsname, DataSourceDefinition dsdef)
        {
            Boolean success = false;
            try
            {
                this.rs.CreateDataSource(parentPath, dsname, false, dsdef, null);
                success = true;
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.Detail.InnerText);
            }
            return success;
        }

        public Boolean Exists(string path)
        {
            if (this.rs.GetItemType(path) == "DataSource")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
